<?php


namespace App\Http\Controllers\Api;

use App\Businesses\BusinessState;
use App\Http\Requests\ApiV2\WishBgImageRequest;
use App\Http\Requests\ApiV2\WishRequest;
use App\Services\Business\Models\Wish;
use App\Services\Business\Models\WishFragment;
use App\Services\Business\Models\WishList;
use App\Services\Member\Interfaces\UserServiceInterface;

use App\Services\Member\Models\User;
use App\Services\Member\Models\UserCreditRecord;
use App\Services\Member\Services\UserService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\Services\Member\Models\FamilyMember;


class WishController extends BaseController
{


    /**
     * @var UserService
     */
    protected $userService;

    protected $businessState;


    public function __construct(

        UserServiceInterface $userService,
        BusinessState        $businessState
    )
    {

        $this->userService = $userService;
        $this->businessState = $businessState;

    }


    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function index(Request $request)
    {


        $size = $request->input('size');
        $wish = Wish::query()
            ->with(['user:id,nick_name,avatar'])
            ->orderBy('created_at', 'desc')->paginate($size);
        return $this->successData(compact('wish'));
    }


    public function detail(Request $request, $id)
    {

        $wish = Wish::query()->with(['user', 'comments' => function ($query) {
            $query->with(['user:id,avatar,nick_name'])->take(10);
        }])->where('id', $id)->firstOrFail();

        $isFollowed = false;
        $isThumbsuped = false;
        if ($this->check()) {
            $isFollowed = $this->userService->isFollowed($this->id(), $wish->user_id);
            $isThumbsuped = $this->userService->isThumbsuped($this->id(), $id, Wish::class);
        }


        return $this->successData(compact('wish', 'isFollowed', 'isThumbsuped'));


    }


    public function store(WishRequest $request, Wish $wish)
    {
        $data = $request->filldata();
        $wish->fill($data)->save();
        return $this->success("发布成功");
    }

    /**
     * 更新心愿
     * @param WishRequest $request
     * @param $id
     * @return JsonResponse
     */
    public function update(WishRequest $request, $id)
    {
        $data = $request->filldata();
        $wish = Wish::query()->where('id', $id)->firstOrFail();
        $wish->fill($data)->save();
        return $this->success(__('更新成功'));

    }


    /**挑战编辑
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function edit(Request $request, $id)
    {


        $wish = Wish::query()
            ->with(['user'])
            ->where('id', $id)
            ->firstOrFail();

        return $this->successData(compact("wish"));

    }


    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function delete(Request $request, $id)
    {
        $wish = Wish::query()->where('id', $id)->firstOrFail();

        if ($wish->fragments()->exists()) {
            return $this->error(__('已有碎片不能删除'));
        }
        $wish->delete();

        return $this->success(__('删除活动成功'));
    }




    /**
     * 碎片详情
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function fragment(Request $request, $id)
    {

        $size = $request->input('size', 10);
        $fragments = WishFragment::query()
            ->with(['images', 'videos'])
            ->where('wish_id', $id)
            ->orderByDesc('created_at')
            ->paginate($size);
        //发布的人
        $users = User::query()
            ->whereIn('id', array_column($fragments->items(), 'user_id'))
            ->select(['id', 'nick_name', 'avatar', 'mobile'])
            ->get()
            ->keyBy('id');
        return $this->successData(compact('fragments', 'users'));

    }


    /**
     * 更新挑战的背景
     * @param WishBgImageRequest $request
     * @return JsonResponse
     */
    public function changeBg(WishBgImageRequest $request)
    {
        $data = $request->filldata();
        $url = $data['thumb'];
        $urlSmall = $data['thumb_small'];
        $wishId = $data['wish_id'];
        $wish = Wish::query()->where('id', $wishId)->first();
        //删除阿里云的数据
        $path = parse_url($wish->thumb, PHP_URL_PATH);
        $pathSmall = parse_url($wish->thumb_small, PHP_URL_PATH);
        $url && Storage::disk('oss')->delete($path, $pathSmall);
        $wish->update(['thumb' => $url, 'thumb_small' => $urlSmall]);
        return $this->successData(compact('url'));


    }

    /**
     * 奖品的置换
     * @param Request $request
     * @return JsonResponse
     */
    public function fulfill(Request $request,$id)
    {

        $today = Carbon::now();
        $wish = Wish::find($id);
        // 检查用户的积分余额是否足够兑换指定的商品

        //todo 暂时只处理学习的积分
        if ($wish->remain_point  < $wish->point) {
            return $this->error(__('积分不够兑换,继续努力'));
        }

        if ($wish->list()->exists()) {
            return $this->error(__('已经兑换过'));
        }
        DB::transaction(function () use ($wish,$today) {
            $wish->update(['status'=>1,'days'=>Carbon::parse($wish->start_at)->diffInDays($today)]);
            WishList::create([
                'user_id' => Auth::id(),
                'wish_id' => $wish->id,
                'point'=>$wish->remain_point,
                'days' =>Carbon::parse($wish->start_at)->diffInDays($today),
            ]);

        });

        // 返回成功响应
        return $this->success(__('心愿兑换成功'));
    }


}
